<script setup lang="ts">
import {ref , computed} from 'vue'
import apiClient from "../axios/axios.ts";
import { Search, User, ShoppingCart, Coin, MagicStick } from '@element-plus/icons-vue'
import LoginDialog from '../components/LoginDialog.vue';
import ShoppingCartDrawer from '../components/ShoppingCartDrawer.vue';
import AiRecommendDialog from '../components/AiRecommendDialog.vue';
import { useUserStore } from '../stores/user.ts';
import { useCartStore } from '../stores/cart.ts';
import {ElMessage} from "element-plus";

const userStore = useUserStore();
const cartStore = useCartStore();
const loginDialogRef = ref<InstanceType<typeof LoginDialog> | null>(null);
const isCartDrawerVisible = ref(false);
const isAiDialogVisible = ref(false);

const isLoggedIn = computed(() => userStore.isLoggedIn);
const userName = computed(() => userStore.user?.name);

const user_search = ref('');
const catelogy_first = ref('All');
interface Category{
  id: number;
  name: string;
  parent_category_id: string;
  description: string
}
interface Product{
  id: number;
  name: string;
  description: string;
  price: number;
  categoryId: string;
  quantity: number;
  imageUrl: string;
}
const categories = ref<Category[]>([
  { id: 1, name: '全部',parent_category_id:'',description:'全部'}
]);
const getCategories = async () =>{
  const response = await apiClient.get<Category[]>('/category/category_id/1');
  response.data.forEach((category:Category) =>{
    categories.value.push(category);
  })
}
const items = ref<Product[]>([]);
const getProducts = async (id:number) =>{
  items.value = [];
  const response = await apiClient.get<Product[]>('/product/category/' + id);
  response.data.forEach((product:Product) => {
    items.value.push(product);
  })
}

const allProducts = ref<Product[]>([]);

const getAllProducts = async () => {
  const res = await apiClient.get<Product[]>('/product');
  allProducts.value = res.data;
};

const chunkedItems = computed(() => {
  const chunkSize = 4;
  const result = [];
  for (let i = 0; i < items.value.length; i += chunkSize) {
    result.push(items.value.slice(i, i + chunkSize));
  }
  return result;
});

const openLoginDialog = () => {
  loginDialogRef.value?.openDialog();
}

const handleAddToCart = (item: Product) => {
  if (!isLoggedIn.value) {
    openLoginDialog();
    ElMessage.info('请先登录后再进行操作');
  } else {
    cartStore.addItem(item.id, 1);
  }
};

const handleLoginSuccess = (user: any) => {
  ElMessage.success(`欢迎回来, ${user.name}!`);
  cartStore.getCart();
};

const logout = () => {
  userStore.clearCredentials();
  cartStore.clearLocalCartState();
  ElMessage.success('您已成功登出');
};

const openCartDrawer = () => {
  if (!isLoggedIn.value) {
    openLoginDialog();
    ElMessage.info('请先登录以查看购物车');
    return;
  }
  cartStore.getCart();
  isCartDrawerVisible.value = true;
};

const openAiDialog = () => {
  isAiDialogVisible.value = true;
};

getCategories()
getProducts(1)
getAllProducts()


</script>

<template>
  <el-container class="layout-container-main">
    <el-header class="layout-header">
      <el-row class="header-row">
        <el-col :span="6" class="logo-area">
          E Commerce Platform
        </el-col>
        <el-col :span="12" class="search-area">
          <div >
            <el-icon color="1a1a1a" :size = "35" style="vertical-align: middle;margin-right: 10px">
              <Search style="color: #9ca3af"/>
            </el-icon>
            <el-input style="width: 500px;height: 50px;--el-input-focus-border-color: orange;--el-input-border-radius: 8px;font-size: 18px" v-model = "user_search" placeholder="搜索"/>
          </div>
        </el-col>
        <el-col :span="6" class="top-right-area">
          <div v-if="isLoggedIn" class="user-info-area">
            <router-link to="/profile">
              <el-icon :size="30" class="top-right-icon"><User /></el-icon>
            </router-link>
            <el-button type="text" @click="logout" class="logout-button">登出</el-button>
          </div>
          <el-icon v-else :size="35" class="top-right-icon" @click="openLoginDialog">
            <User />
          </el-icon>
          <el-badge :value="cartStore.cart.totalQuantity" :hidden="!isLoggedIn || cartStore.cart.totalQuantity === 0" class="cart-badge">
            <el-icon :size="35" class="top-right-icon" @click="openCartDrawer">
              <ShoppingCart />
            </el-icon>
          </el-badge>
          <el-icon :size = "35" class="top-right-icon">
              <router-link to="/admin/products" ><Coin class="top-right-icon-2"/></router-link>
          </el-icon>
          <el-icon :size="35" class="top-right-icon" @click="openAiDialog" style="color: orange;">
            <MagicStick />
          </el-icon>
        </el-col>
      </el-row>
    </el-header>
    <el-header style="background-color: orange;align-items: center;display: flex;">
      <el-radio-group v-model="catelogy_first"  class="custom-transparent-radio" >
        <el-radio-button
            v-for="option in categories"
            :key="option.id"
            :label="option.id"
            :value="option.id"
            @click="getProducts(option.id)"
        >{{ option.name }}
        </el-radio-button>
      </el-radio-group>
    </el-header>
    <el-main class="layout-body">
      <el-row v-for="(rowItems, rowIndex) in chunkedItems" :key="rowIndex" :gutter="30" class="main-el-row">
        <el-col v-for="(item) in rowItems" :key="item.id" :span="6">
          <router-link :to="`/product/${item.id}`" style="text-decoration: none;">
            <div class="grid-content ep-bg-purple">
              <el-image style="width: 100% ;aspect-ratio: 1;" :src="item.imageUrl"/>
              <el-row style="margin-top: 10px">
                <el-text truncated style="margin-left: 15px;font-size: 22px;font-weight: bold ;color: black">{{ item.name }}</el-text>
              </el-row>
              <el-row>
                <el-text truncated style="margin-left: 15px;font-size: 15px;margin-right: 15px">{{ item.description }}</el-text>
              </el-row>
              <el-row style="margin-top: 20px;margin-left: 15px;margin-right: 15px;">
                <el-col :span="14" style="text-align: left;margin-bottom: 10px;">
                  <el-text truncated style="font-size: 25px;font-weight: bold;color: orange;">{{"￥" + item.price}}</el-text>
                </el-col>
                <el-col :span="10">
                  <el-button class="el-buy-button" @click.prevent="handleAddToCart(item)" style="background-color: orange;color: white;height: 38px;border-width: 0;border-radius: 8px;">加入购物车</el-button>
                </el-col>
              </el-row>
            </div>
          </router-link>
        </el-col>
      </el-row>
    </el-main>
    <login-dialog ref="loginDialogRef" @login-success="handleLoginSuccess"></login-dialog>
    <shopping-cart-drawer v-model:visible="isCartDrawerVisible" @close="isCartDrawerVisible = false" />
    <ai-recommend-dialog v-model="isAiDialogVisible" :products="allProducts" />
  </el-container>
</template>

<style scoped>
.main-el-row{
  margin-left: 100px !important;
  margin-right: 100px !important;
  margin-bottom: 30px !important;
}
.layout-body{
  flex-grow: 1;
  background-color: #f9f9f9;
  min-height: 660px;
}
.grid-content {
  border-radius: 8px;
  min-height: 36px;
  text-align: center;
  background-color: white;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.grid-content:hover{
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.16), 0 0 6px rgba(0, 0, 0, 0.04);
}


.layout-header{
  --el-header-padding: 0;
  height: 70px;
}
.header-row {
  height: 100%;
  margin-left: 150px;
  margin-right: 150px;
}
.logo-area{
  display: flex;
  align-items: center;
  color: orange;
  font-size: 25px;
  font-weight: 900;
}
.search-area{
  align-items: center;
  align-content: center;
}
.top-right-area{
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.top-right-icon{
  margin-left: 35px !important;
}
.top-right-icon:hover{
  color: orange;
  cursor: pointer;
  transition: color 0.3s;
}
.top-right-icon-2{
  color: #213547;
}

.top-right-icon-2:hover{
  color: orange;
  cursor: pointer;
  transition: color 0.3s;
}
.custom-transparent-radio{
  margin-left: 120px;
  height: 40px;
}
.custom-transparent-radio :deep(.el-radio-button) {
  margin-left: 0 !important;
}
.custom-transparent-radio :deep(.el-radio-button .el-radio-button__inner) {
  background-color: transparent !important; /* 背景透明 */
  color: white !important; /* 字体白色 */
  border: none !important; /* 无边框 */
  box-shadow: none !important; /* 移除默认阴影和边框效果 */
  border-radius: 4px !important; /* 可以保留或移除圆角 */
  font-weight: 500;
  font-size: 18px;
  margin-right: 18px;
  font-family: GeistSans, "GeistSans Fallback";
  height: 40px;
  align-content: center;
}

/* 选中状态的样式 */
.custom-transparent-radio :deep(.el-radio-button.is-active .el-radio-button__inner) {
  background-color: white !important; /* 选中时背景变白 */
  color: orange !important; /* 选中时字体变橘色 */
}

/* hover 状态的样式 */
.custom-transparent-radio :deep(.el-radio-button:hover .el-radio-button__inner) {
  background-color: rgba(255, 255, 255, 0.2) !important; /* hover 时背景轻微变白 */
}
.el-buy-button:hover{
  box-shadow: 0 6px 8px rgba(255, 165, 0, 0.5), 0 0 6px rgba(255, 165, 0, 0.04);
}
.user-info-area {
  display: flex;
  align-items: center;
}
.user-name-text {
  margin-right: 15px;
}
.logout-button {
  margin-left: 15px;
}
.cart-badge {
  margin-left: 0px;
}
</style>
